<?php

namespace app\admin\controller\ykjp\sell;

use app\common\controller\Backend;
use think\Db;

/**
 * 销售出库单
 *
 * @icon fa fa-circle-o
 */
class DeliveryFinancial extends Backend {

    /**
     * DeliveryFinancial模型对象
     * @var \app\admin\model\ykjp\sell\DeliveryFinancial
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\ykjp\sell\DeliveryFinancial;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusListList", $this->model->getStatusListList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看详情页
     */
    public function detail() {
        $ids = $this->request->param("ids");
        if ($ids == "") {
            $this->error("fail", "sell/DeliveryFinancial/index");
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = Db::name('ykjp_delivery')
                ->where($where)
                ->where('firmid', $this->auth->firmid)
                ->where("id", $ids)
                ->select();
        // halt($list);
        $dModel = new \app\admin\model\ykjp\sell\deliveryPro;
        $strProduct = $dModel->with(['products'])->where("delivery_id", $ids)->where('products.firmid', $this->auth->firmid)->select();
        foreach ($strProduct as $key => $val) {
            $pro = json_decode($val['products']['prop']);
            $val['products']['prop'] = $this->model->object_array($pro);

            //根据wp_id查询出库位置
            $wp_id = $strProduct[$key]['wp_id'];
            $arr = Db::name('ykjp_wp_relationship')->where('id', $wp_id)->where('firmid', $this->auth->firmid)->field('warehouse_id,partition_id')->find();

            //获取仓库名称
            $w_name = Db::name('ykjp_warehouse')->where('id', $arr['warehouse_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['w_name'] = $w_name['name'];

            //获取库区名称
            $p_name = Db::name('ykjp_partition')->where('id', $arr['partition_id'])->where('firmid', $this->auth->firmid)->field('name')->find();
            $strProduct[$key]['p_name'] = $p_name['name'];
        }
        // halt($strProduct);

        $this->assign("detail", $list);
        $this->assign("product", $strProduct);
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function audit($ids = null) {

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        //判断通过还是驳回 （pass 通过  reject 驳回)
        if ($this->request->param("act") == "pass") {  //通过
            $data = array("status_list" => 5, "reviewer_id" => $this->auth->id, "updatetime" => time());
            $update = $this->model
                    ->where("status_list", 3)
                    ->where('firmid', $this->auth->firmid)
                    ->where("id", "in", $ids)
                    ->update($data);
            if ($update) {
                $this->success(null, null, array("result" => "success"));
            }
            $this->error("operation fail");
        } elseif ($this->request->param("act") == "reject") {  //驳回
            // 获取数据
            $cause = $this->request->param('cause');  //审核失败原因
            $time = time();
            $data = array("status_list" => 4, "reviewer_id" => $this->auth->id, "updatetime" => $time, 'cause' => $cause);

            //获取销售副表的关联表参数
            $wp_arr = Db::name('ykjp_delivery_product')
                    ->field('nums,wp_id')
                    ->where("delivery_id", "in", $ids)
                    ->where('firmid', $this->auth->firmid)
                    ->select();
            // halt($wp_arr);
            // 启动事务
            Db::startTrans();
            try {

                //一、更新销售出库单状态
                Db::name('ykjp_delivery')->where("status_list", 3)->where('firmid', $this->auth->firmid)->where("id", "in", $ids)->update($data);

                //二、更新关联表
                for ($i = 0; $i < count($wp_arr); $i++) {
                    Db::name('ykjp_wp_relationship')
                            ->where('firmid', $this->auth->firmid)
                            ->where('id', $wp_arr[$i]['wp_id'])
                            ->update([
                                'freeze' => Db::raw('freeze-' . $wp_arr[$i]['nums']),
                                'inventory' => Db::raw('inventory+' . $wp_arr[$i]['nums']),
                                'updatetime' => Db::raw($time),
                    ]);
                }

                // 提交事务
                Db::commit();
                $this->success(null, null, array("result" => "成功"));
            } catch (PDOException $e) {

                Db::rollback();
                $this->error('提交失败');
            } catch (Exception $e) {

                Db::rollback();
                $this->error('提交失败');
            }

            $this->error("提交失败");
        }

        $this->error("Illegal operation");
    }

    // public function audit($ids=null){
    //     list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    //     //判断通过还是驳回 （pass 通过  reject 驳回)
    //     if($this->request->param("act") == "pass"){  //通过
    //         $time = time();
    //         $data = array("status_list" => 5,"reviewer_id" => $this->auth->id,"updatetime" => $time);
    //         /*
    //             首先修改出库单状态，然后
    //             通过前台传递过来的ids列表查询销售出库单的‘销售单ID’字段和《销售出库单副表》，获取销售出库单副表中的‘出库数量’、‘关联表id’和‘产品ID’字段。
    //             根据获取的字段:
    //                 更新销售单表
    //                 插入流水表
    //                 更新关联表
    //                 更新商品表
    //                 更新仓库表
    //                 更新库区表
    //         */
    //         //获取 销售出库单的‘销售单ID’字段
    //         $sell_id_arr = Db::name('ykjp_delivery')->field('sell_id')->where("id","in",$ids)->where('firmid',$this->auth->firmid)->select();
    //         // 处理结果为列表
    //         for($i=0; $i<count($sell_id_arr); $i++){
    //             if($i == 0){
    //                 $sell_id_list = $sell_id_arr[$i]['sell_id'];
    //             }else{
    //                 $sell_id_list .= ',';
    //                 $sell_id_list .= $sell_id_arr[$i]['sell_id'];
    //             }
    //         }
    //         //获取销售副表的关联表参数
    //         $wp_arr = Db::name('ykjp_delivery_product')
    //             ->alias('d')
    //             ->join('wp_relationship w','d.wp_id = w.id')
    //             ->field('d.nums,d.wp_id,d.product_id,w.warehouse_id,w.partition_id')
    //             ->where("d.delivery_id","in",$ids)
    //             ->where('d.firmid',$this->auth->firmid)
    //             ->where('w.firmid',$this->auth->firmid)
    //             ->select();
    //         // 启动事务
    //         Db::startTrans();
    //         try{
    //             //一、更新销售出库单状态
    //             Db::name('ykjp_delivery')->where("status_list",3)->where('firmid',$this->auth->firmid)->where("id","in",$ids)->update($data);
    //             //二、更新销售单状态
    //             Db::name('ykjp_sell')->where("status_list",5)->where('firmid',$this->auth->firmid)->where("id","in",$sell_id_list)->update(['status_list'=>6,'updatetime'=>$time]);
    //             //三、
    //             for($i=0; $i<count($wp_arr); $i++){
    //                 //插入流水表
    //                 Db::name('ykjp_inventory_statement')->insert([
    //                     'firmid'        => $this->auth->firmid,
    //                     'product_id'    => $wp_arr[$i]['product_id'],
    //                     'warehouse_id'  => $wp_arr[$i]['warehouse_id'],
    //                     'partition_id'  => $wp_arr[$i]['partition_id'],
    //                     'number'        => $wp_arr[$i]['nums'],
    //                     'type'          => '销售出库',
    //                     'updatetime'    => $time,
    //                 ]);
    //                 //更新关联表
    //                 Db::name('ykjp_wp_relationship')
    //                     ->where('firmid',$this->auth->firmid)
    //                     ->where('id',$wp_arr[$i]['wp_id'])
    //                     ->update([
    //                         'freeze'        => Db::raw('freeze-'.$wp_arr[$i]['nums']),
    //                         'updatetime'    => Db::raw($time),
    //                     ]);
    //                 //更新商品表
    //                 Db::name('ykjp_product')
    //                     ->where('firmid',$this->auth->firmid)
    //                     ->where('id',$wp_arr[$i]['product_id'])
    //                     ->update([
    //                         'inventory'        => Db::raw('inventory-'.$wp_arr[$i]['nums']),
    //                         'updatetime'    => Db::raw($time),
    //                     ]);
    //                 //更新仓库表
    //                 Db::name('ykjp_warehouse')
    //                     ->where('firmid',$this->auth->firmid)
    //                     ->where('id',$wp_arr[$i]['warehouse_id'])
    //                     ->update([
    //                         'inventory'     => Db::raw('inventory-'.$wp_arr[$i]['nums']),
    //                         'updatetime'    => Db::raw($time),
    //                     ]);
    //                 // 更新库区表
    //                 Db::name('ykjp_partition')
    //                     ->where('firmid',$this->auth->firmid)
    //                     ->where('id',$wp_arr[$i]['partition_id'])
    //                     ->update([
    //                         'inventory'     => Db::raw('inventory-'.$wp_arr[$i]['nums']),
    //                         'updatetime'    => Db::raw($time),
    //                     ]);
    //             }
    //             // 提交事务
    //             Db::commit();
    //             $this->success(null,null,array("result" => "成功"));
    //         } catch (PDOException $e) {
    //             Db::rollback();
    //             $this->error('提交失败');
    //         } catch (Exception $e) {
    //             Db::rollback();
    //             $this->error('提交失败');
    //         }
    //         $this->error("提交失败");
    //     }elseif($this->request->param("act") == "reject"){  //驳回
    //         // 获取数据
    //         $time = time();
    //         $data = array("status_list" => 4,"reviewer_id" => $this->auth->id,"updatetime" => $time);
    //         //获取销售副表的关联表参数
    //         $wp_arr = Db::name('ykjp_delivery_product')
    //             ->field('nums,wp_id')
    //             ->where("delivery_id","in",$ids)
    //             ->where('firmid',$this->auth->firmid)
    //             ->select();
    //         // halt($wp_arr);
    //         // 启动事务
    //         Db::startTrans();
    //         try{
    //             //一、更新销售出库单状态
    //             Db::name('ykjp_delivery')->where("status_list",3)->where('firmid',$this->auth->firmid)->where("id","in",$ids)->update($data);
    //             //二、更新关联表
    //             for($i=0; $i<count($wp_arr); $i++){
    //                 Db::name('ykjp_wp_relationship')
    //                     ->where('firmid',$this->auth->firmid)
    //                     ->where('id',$wp_arr[$i]['wp_id'])
    //                     ->update([
    //                         'freeze'       => Db::raw('freeze-'.$wp_arr[$i]['nums']),
    //                         'inventory'    => Db::raw('inventory+'.$wp_arr[$i]['nums']),
    //                         'updatetime'   => Db::raw($time),
    //                     ]);
    //             }
    //             // 提交事务
    //             Db::commit();
    //             $this->success(null,null,array("result" => "成功"));
    //         } catch (PDOException $e) {
    //             Db::rollback();
    //             $this->error('提交失败');
    //         } catch (Exception $e) {
    //             Db::rollback();
    //             $this->error('提交失败');
    //         }
    //         $this->error("提交失败");
    //     }
    //     $this->error("Illegal operation");
    // }
}
